import 'dart:io';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:jump_scape/js_ui/js_activity/js_about.dart';
import 'package:jump_scape/js_ui/js_activity/js_coin_shop.dart';
import 'package:jump_scape/js_ui/js_activity/js_setting.dart';
import 'package:jump_scape/js_ui/js_dialog/js_personal.dart';
import 'package:jump_scape/js_ui/js_widget/js_image_view.dart';
import 'package:jump_scape/js_ui/js_widget/js_style.dart';
import 'package:jump_scape/js_util/js_audio_play.dart';

import '../../js_data/js_box/js_init.dart';
import '../../js_data/js_event.dart';
import '../../js_data/js_member.dart';
import '../../objectbox.g.dart';
import 'js_personal_edit.dart';

class JsPersonalActivity extends StatefulWidget {
  static const url = 'personal';
  const JsPersonalActivity({super.key});

  @override
  State<StatefulWidget> createState() => _JsPersonalActivity();
}

class _JsPersonalActivity extends State<JsPersonalActivity> with WidgetsBindingObserver {
  var isPlaying = false;
  var isCancelAudioState = false;
  String _name = '';
  String _userId = '';
  String _balance = '0';

  @override
  void initState() {
    super.initState();
    JsEventManager.statPage(page: JsEventName.jsNameMine);
    _init();
    JsMember().synchronizationMember(onSuccess: (_) {}, onFailed: (_) {});
    JsAudioPlay().init();

    WidgetsBinding.instance.addObserver(this);
  }

  @override
  void dispose() {
    super.dispose();
    JsAudioPlay().releaseFlauto();
    WidgetsBinding.instance.removeObserver(this);
  }

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    super.didChangeAppLifecycleState(state);
    switch (state) {
      case AppLifecycleState.resumed:
        debugPrint("[lifecycle] Application entry foreground======");
        break;
      case AppLifecycleState.paused:
        debugPrint("[lifecycle] Application enter background======");
        JsAudioPlay().stopPlayer();
        break;
      default:
        debugPrint("[lifecycle] state=$state");
        break;
    }
  }

  _init() async {
    final setting = await JsObjectBox.setting;
    var member = JsObjectBox.memberBox.query(MemberBox_.userId.equals(setting.userId)).build().findFirst();
    if (member != null) {
      _name = member.name;
      _userId = member.userId;
      _balance = member.balance;
      if (_balance.isEmpty) _balance = '0';
      setState(() {});
    }
  }

  @override
  Widget build(BuildContext context) {
    return WillPopScope(
      onWillPop: () => Future.value(false),
      child: Scaffold(
        body: Stack(
          children: [
            jsImage('assets/image/ic_records_bg.png', width: double.infinity, height: double.infinity, fit: BoxFit.cover),
            Padding(
              padding: EdgeInsets.only(top: ScreenUtil().statusBarHeight),
              child: Row(
                children: [
                  InkWell(
                    onTap: () {
                      JsAudioPlay().stopPlayer();
                      if (Navigator.canPop(context)) {
                        Navigator.pop(context);
                      }
                    },
                    child: Container(
                      padding: EdgeInsets.fromLTRB(18.r, 15.r, 18.r, 0),
                      child: jsImage('assets/image/ic_finish.png', width: 64.r, height: 64.r),
                    ),
                  ),
                  Spacer(),
                  InkWell(
                    onTap: () async {
                      JsAudioPlay().stopPlayer();
                      await Navigator.pushNamed(context, JsPersonalEditActivity.url);

                      _init();
                    },
                    child: Container(
                      padding: EdgeInsets.fromLTRB(18.r, 15.r, 18.r, 0),
                      child: jsImage('assets/image/ic_personal_edit.png', width: 64.r, height: 64.r),
                    ),
                  ),
                ],
              ),
            ),
            Container(
              width: double.infinity,
              height: double.infinity,
              margin: EdgeInsets.fromLTRB(26.r, ScreenUtil().statusBarHeight + 40.r, 26.r, 0),
              clipBehavior: Clip.antiAlias,
              decoration: jsShapeRoundT(radius: 200.r, color: Colors.white),
              child: SingleChildScrollView(
                child: Column(
                  children: [
                    jsImage('assets/gif/ic_personal.gif', width: 160.r, fit: BoxFit.fitWidth, padding: EdgeInsets.only(top: 9.r, bottom: 6.r)),
                    Text(_name, style: jsTextStyle(font: JsTextFont.PoetsenOne, fontColor: Colors.black, fontSize: 16.r)),
                    InkWell(
                      child: Padding(
                        padding: EdgeInsets.all(10.r),
                        child: Row(
                          mainAxisAlignment: MainAxisAlignment.center,
                          mainAxisSize: MainAxisSize.min,
                          children: [
                            Text('ID：$_userId', style: jsTextStyle(font: JsTextFont.PoetsenOne, fontColor: Colors.black, fontSize: 16.r)),
                            Container(
                              margin: EdgeInsets.only(left: 9.r),
                              clipBehavior: Clip.antiAlias,
                              decoration: jsShapeRound(radius: 4.r, shadows: [
                                BoxShadow(offset: Offset(1.r, 1.r), blurRadius: 2.r, color: Color(0xFFC9C9C9)),
                              ]),
                              child: jsImage('assets/image/ic_personal_copy.png', width: 26.r, fit: BoxFit.fitWidth),
                            ),
                          ],
                        ),
                      ),
                      onTap: () async {
                        ScaffoldMessenger.of(context).showSnackBar(
                          SnackBar(
                            content: Text('Copy success', style: jsTextStyle(font: JsTextFont.PoetsenOne, fontColor: Colors.white, fontSize: 20.r)),
                          ),
                        );

                        await Clipboard.setData(ClipboardData(text: _userId));
                      },
                    ),
                    Container(
                      margin: EdgeInsets.fromLTRB(34.r, 4.r, 34.r, 0),
                      clipBehavior: Clip.antiAlias,
                      decoration: jsShapeRound(radius: 20.r, shadows: [
                        BoxShadow(offset: Offset(2.r, 4.r), color: Color(0xFFAE6060).withOpacity(0.12), blurRadius: 5.r),
                      ]),
                      child: InkWell(
                        child: Stack(
                          children: [
                            jsImage('assets/image/ic_personal_coins_bg.png', width: double.infinity, fit: BoxFit.fitWidth),
                            Positioned.fill(
                              child: Row(
                                crossAxisAlignment: CrossAxisAlignment.start,
                                children: [
                                  Expanded(child: jsImage('assets/image/ic_icon_big.png', fit: BoxFit.fitWidth, padding: EdgeInsets.fromLTRB(28.r, 11.r, 37.r, 0))),
                                  Container(width: 1.r, height: 40.r, color: Colors.black, margin: EdgeInsets.only(top: 19.r)),
                                  Expanded(
                                    child: Column(
                                      mainAxisAlignment: MainAxisAlignment.center,
                                      children: [
                                        Text('My Coins', style: jsTextStyle(font: JsTextFont.October_Devanagari_Medium, fontColor: Colors.black, fontSize: 12.r)),
                                        SizedBox(height: 5.r),
                                        Text(_balance, style: jsTextStyle(font: JsTextFont.October_Devanagari_Medium, fontColor: Colors.black, fontSize: 20.r)),
                                      ],
                                    ),
                                  ),
                                ],
                              ),
                            ),
                          ],
                        ),
                        onTap: () async {
                          JsAudioPlay().stopPlayer();
                          await Navigator.pushNamed(context, JsCoinShopActivity.url);

                          _init();
                        },
                      ),
                    ),
                    Container(
                      margin: EdgeInsets.fromLTRB(22.r, 22.r, 22.r, 0),
                      clipBehavior: Clip.antiAlias,
                      decoration: jsShapeRound(radius: 12.r, shadows: [
                        BoxShadow(offset: Offset(1.r, 1.r), blurRadius: 4.r, color: Color(0xFFC9C9C9)),
                      ]),
                      child: InkWell(
                        child: Stack(
                          children: [
                            jsImage('assets/image/ic_personal_item.png', width: double.infinity, fit: BoxFit.fitWidth),
                            Positioned(
                              left: 30.r,
                              right: 0,
                              top: 0,
                              bottom: 0,
                              child: Row(
                                children: [
                                  Text("Phonetics：", style: jsTextStyle(font: JsTextFont.PoetsenOne, fontColor: Colors.white, fontSize: 13.r)),
                                  Spacer(),
                                  InkWell(
                                    child: jsImage(
                                      isPlaying ? 'assets/svga/ic_personal_audio.svga' : 'assets/image/ic_personal_audio.png',
                                      width: 31.r,
                                      height: isPlaying ? null : 19.r,
                                      fit: isPlaying ? BoxFit.fitWidth : BoxFit.contain,
                                      alignment: Alignment.centerLeft,
                                      padding: EdgeInsets.fromLTRB(10.r, 5.r, 27.r, 5.r),
                                    ),
                                    onTap: () async {
                                      if (isPlaying) {
                                        JsAudioPlay().stopPlayer();
                                      } else {
                                        final setting = await JsObjectBox.setting;
                                        final member = JsObjectBox.memberBox.query(MemberBox_.userId.equals(setting.userId)).build().findFirst();
                                        if (member == null) return;
                                        final audioPath = await member.audioPathReal();
                                        debugPrint("[audioPath] 🎵 $audioPath");

                                        if (audioPath.isEmpty || !File(audioPath).existsSync()) {
                                          jsShowAudioDialog(context);
                                          return;
                                        }

                                        JsAudioPlay().resetCallback(audioPath, (bool isFinish, int s) {
                                          isPlaying = !isFinish;
                                          if (mounted) setState(() {});
                                        });
                                        JsAudioPlay().startPlayer(audioPath, (bool isFinish, int s) {
                                          isPlaying = !isFinish;
                                          if (mounted) setState(() {});
                                        });
                                      }
                                    },
                                  ),
                                ],
                              ),
                            ),
                          ],
                        ),
                        onTap: () {
                          jsShowAudioDialog(context);
                        },
                      ),
                    ),
                    Container(
                      margin: EdgeInsets.fromLTRB(22.r, 15.r, 22.r, 0),
                      clipBehavior: Clip.antiAlias,
                      decoration: jsShapeRound(radius: 12.r, shadows: [
                        BoxShadow(offset: Offset(1.r, 1.r), blurRadius: 4.r, color: Color(0xFFC9C9C9)),
                      ]),
                      child: InkWell(
                        child: Stack(
                          children: [
                            jsImage('assets/image/ic_personal_item.png', width: double.infinity, fit: BoxFit.fitWidth),
                            Positioned(
                              left: 30.r,
                              right: 30.r,
                              top: 0,
                              bottom: 0,
                              child: Row(
                                children: [
                                  Text("About", style: jsTextStyle(font: JsTextFont.PoetsenOne, fontColor: Colors.white, fontSize: 13.r)),
                                  Spacer(),
                                  jsImage('assets/image/ic_personal_arrow.png', width: 28.r, fit: BoxFit.fitWidth),
                                ],
                              ),
                            ),
                          ],
                        ),
                        onTap: () {
                          Navigator.pushNamed(context, JsAboutActivity.url);
                          JsAudioPlay().stopPlayer();
                        },
                      ),
                    ),
                    Container(
                      margin: EdgeInsets.fromLTRB(22.r, 15.r, 22.r, 0),
                      clipBehavior: Clip.antiAlias,
                      decoration: jsShapeRound(radius: 12.r, shadows: [
                        BoxShadow(offset: Offset(1.r, 1.r), blurRadius: 4.r, color: Color(0xFFC9C9C9)),
                      ]),
                      child: InkWell(
                        child: Stack(
                          children: [
                            jsImage('assets/image/ic_personal_item.png', width: double.infinity, fit: BoxFit.fitWidth),
                            Positioned(
                              left: 30.r,
                              right: 30.r,
                              top: 0,
                              bottom: 0,
                              child: Row(
                                children: [
                                  Text("Setting", style: jsTextStyle(font: JsTextFont.PoetsenOne, fontColor: Colors.white, fontSize: 13.r)),
                                  Spacer(),
                                  jsImage('assets/image/ic_personal_arrow.png', width: 28.r, fit: BoxFit.fitWidth),
                                ],
                              ),
                            ),
                          ],
                        ),
                        onTap: () {
                          Navigator.pushNamed(context, JsSettingActivity.url);
                          JsAudioPlay().stopPlayer();
                        },
                      ),
                    ),
                    SizedBox(height: 224.r),
                  ],
                ),
              ),
            ),
            Align(
              alignment: Alignment.bottomCenter,
              child: IgnorePointer(
                child: jsImage('assets/image/ic_home_bg_bottom.png', width: double.infinity, fit: BoxFit.fitWidth),
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildAudioState() {
    return Container(
      width: double.infinity,
      height: double.infinity,
      color: Colors.black.withOpacity(0.55),
      child: Column(
        mainAxisAlignment: MainAxisAlignment.end,
        children: [
          Spacer(),
          Text(isCancelAudioState ? "Release Cancel" : "Release Send", style: jsTextStyle(font: JsTextFont.October_Devanagari_Medium, fontSize: 16.r, fontColor: Colors.white)),
          SizedBox(height: 28.r),
          Stack(
            children: [
              jsImage("assets/image/ic_audio_bg.png", width: double.infinity, fit: BoxFit.fitWidth),
              jsImage(isCancelAudioState ? 'assets/image/ic_audio.png' : 'assets/svga/ic_audio.svga', height: 50.r, fit: BoxFit.fitHeight),
              Container(
                clipBehavior: Clip.antiAlias,
                decoration: jsShapeRound(radius: 40.r, shadows: [
                  BoxShadow(offset: Offset(1.r, 1.r), blurRadius: 4.r, color: Color(0xFFC9C9C9)),
                ]),
                child: jsImage(isCancelAudioState ? "assets/image/ic_audio_btn.png" : "assets/image/ic_audio_btn_s.png", width: 80.r, fit: BoxFit.fitWidth),
              ),
            ],
          ),
        ],
      ),
    );
  }
}
